package com.ks.base;

import com.ks.util.HtmlUtil;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class BaseAction {

    protected final static String SUCCESS = "success";

    private final static String MSG = "msg";


    /**
     * 获取ip地址
     *
     * @param request
     * @return
     */
    protected String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * ActionMap 统一从这里获取
     *
     * @return
     */
    protected Map<String, Object> getRootMap() {

        return new HashMap<>();
    }

    protected ModelAndView forword(String viewName, Map<String, Object> context) {
        return new ModelAndView(viewName, context);
    }

    protected ModelAndView error(String errMsg) {
        return new ModelAndView("error");
    }

    /**
     * 提示成功信息
     *
     * @param message
     */
    protected void sendSuccessMessage(HttpServletResponse response, String message) {
        Map<String, Object> result = new HashMap<>();
        result.put(SUCCESS, true);
        result.put(MSG, message);
        HtmlUtil.writerJson(response, result);
    }

    /**
     * 提示失败信息
     *
     * @param message 提示信息
     */
    protected void sendFailureMessage(HttpServletResponse response, String message) {
        Map<String, Object> result = new HashMap<>();
        result.put(SUCCESS, false);
        result.put(MSG, message);
        HtmlUtil.writerJson(response, result);
    }

}
